import { Form, Input, Radio } from 'antd'
import { debounce } from 'lodash-es'

type PageProps = {
  isShowTag?: boolean
  backendList: any
  tagList: any
  handleSearch: any
}

const { Search } = Input

export default function SearchBar({ isShowTag = false, backendList, tagList, handleSearch }: PageProps) {
  const [form] = Form.useForm()
  const { validateFields } = form

  // 处理数据
  const handleValues = (values: any) => {
    Object.keys(values).forEach((key) => {
      !values[key] && (delete values[key])
    })

    return values
  }

  // 数据收集
  const onEmit = async () => {
    const values = await validateFields()
    const vals = handleValues(values)

    handleSearch(vals)
  }

  // 版本切换
  const onChangeVersion = () => {
    onEmit()
  }

  // 搜索
  const onSearch = debounce(() => {
    onEmit()
  }, 500)

  // 版本
  const showVersion = (
    <Form.Item name="version" noStyle>
      <Radio.Group buttonStyle="solid" defaultValue={0} onChange={onChangeVersion}>
        <Radio.Button value={0}>全部</Radio.Button>
        <Radio.Button value={18}>React18</Radio.Button>
        <Radio.Button value={17}>React17</Radio.Button>
        <Radio.Button value={16}>&lt;=React16</Radio.Button>
      </Radio.Group>
    </Form.Item>
  )

  // 后台语言
  const showBackend = () => {
    return (
      <div className="publish-version mb-3">
        <Form.Item name="backendId" noStyle>
          <Radio.Group buttonStyle="solid" className="mr-5" defaultValue={0} onChange={onChangeVersion}>
            <Radio.Button value={0}>全部</Radio.Button>
            {backendList?.length > 0 && backendList.map((back: any) => {
              return (
                <Radio.Button value={back.id} key={back.id}>{back.backendName}</Radio.Button>
              )
            })}
          </Radio.Group>
        </Form.Item>
      </div>
    )
  }

  // 标签
  const showTag = (
    <Form.Item name="tagId" noStyle>
      <Radio.Group buttonStyle="solid" className="mr-5" defaultValue={0} onChange={onChangeVersion}>
        <Radio.Button value={0}>全部</Radio.Button>
        {tagList?.length > 0 && tagList.map((tag: any) => {
          return (
            <Radio.Button value={tag.id} key={tag.id}>{tag.tagName}</Radio.Button>
          )
        })}
      </Radio.Group>
    </Form.Item>
  )

  return (
    <Form className="app-searchbar-form" form={form} layout="vertical" name="basic" autoComplete="off" preserve={false} requiredMark={false}>
      <div className="app-page-search mb-4">
        {isShowTag && showBackend()}
        <div className="article-tags flex justify-between">
          {isShowTag && showTag}
          {showVersion}
          <Form.Item name="title" className="app-search-title-form relative none">
            <Search allowClear enterButton onSearch={onSearch} placeholder="请输入关键字搜索" style={{ width: '20rem' }} />
          </Form.Item>
        </div>
      </div>
    </Form>
  )
}
